Les 3 - Vue3 components
Les overzicht
- De algemene structuur van Vue3 beter begrijpen en onderzoeken wat de architectuur is en hoe een Vue applicatie opgebouwd wordt.
Samenvatting
- Vue folder structuur en architectuur
- Deel 2 van de TOH applicatie bouwen
Ons eerste component
- Button needs to be same as the MainLayout button
- Copy / paste -> issue with repetition and maintainability
- CUSTOM COMPONENT -> Styled button
- Show with slot and with props
- Also use in MainLayout
Stopped here
Stap 4 - Navigate to details page
- useRouter in HeroesView
- add onclick handler to details button which navigates to specific hero page
- Show with hardcoded value and then with the actual value
- ? -> not strictly needed because of v-if but can't hurt /shrug
<script setup lang="ts">
import StyledButton from "@/components/StyledButton.vue";
import { ref, type Ref } from "vue";
interface Hero {
number: number;
name: string;
}
const hero: Ref<Hero | null> = ref(null);
</script>
<template>
<template v-if="hero">
<div class="title">{{ hero.name }} details!</div>
<div>id: {{ hero.number }}</div>
<div>name: <input :value="hero.name" /></div>
<StyledButton>Back</StyledButton>
</template>
</template>
<style scoped>
.title {
font-size: 1.5rem;
color: grey;
font-weight: bold;
margin-top: 1rem;
margin-bottom: 1rem;
}
- Change the hero variable to showcase it works
Stap 5 - refactor reusable things
-
Interface Hero wordt meerdere keren gebruikt -> naar een aparte file -> In dit project zeker ok omdat het niet zo groot is, voor grotere projecten gaan we dat typisch anders doen
-
.title common naar main.css
-
Heroes list ff dupliceren -> Voorlopig, wordt opgelost in 1 van de volgende lessen
-
lifecycle component
onMounted-> Uitleggen wat de lifecycle van een component is -
useRoute om de huidige route te kunnen gebruiken
onMounted(() => {
const heroID = Number(route.params.id)
})
- Waarom noemt het id? -> Zie router
- Find hero in list with the correct id
- default undefined or ??
null - ref zonder waarde is altijd undefined
- ternary operator; null coalescing or full if/else
Stap 6 - No hero found
- Add v-if template no hero found (class title)
- Show v-if / v-else
Stap 7 - Back button
useRouter- As we're used to it OR
router.go(-1)
Stap 8 - Two way binding
- Tot nu toe 1 way binding -> Properties komen binnen in de html en worden getoond
- 2 way = als de values in de html geupdate worden -> Rendered opnieuw met nieuwe waarden
- 2 way binding kunnen we doen met
v-model - Door
v-modelte declareren op een variabele wordt die variabele gewatched voor 2 way binding
Stap 9 - Autorefresh ipv manual refresh
- watch toevoegen
watch(
() => route.params.id,
(newID) => {
console.log(newID)
initialiseHero()
}
)
- immediate om onmount te skippen
- Eerste param van watch moet een functie zijn tenzij het een ref is dan niet
Conclusie
- Componenten
- Pages / Views
- Layouts
- Identificeren van deze dingen